package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
)

/*
   Author: mahaiyuan
   Date: 2021/7/14 5:14 下午
   Description:
*/

var upgrader = websocket.Upgrader{
	//允许跨域
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func main() {
	engine := gin.Default()
	engine.GET("/hello", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"errno": 0, "errmsg": "succ"})
	})
	engine.GET("/ping", ping)
	engine.Run("127.0.0.1:8080")
}

func ping(c *gin.Context) {
	//升级为websocket协议
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Fatal("upgrade error.", err)
		return
	}
	defer conn.Close()

	for true {
		messageType, bytes, err := conn.ReadMessage()
		if err != nil {
			log.Fatal("read data error.", err)
			break
		}
		fmt.Printf("got data is %s\n", bytes)
		if err = conn.WriteMessage(messageType, []byte("pong")); err != nil {
			log.Fatal("write data error.", err)
			break
		}
	}
}